﻿using System;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.Xml;

using NetStsAdm.NetStsAdmService;

namespace NetStsAdm
{
    /// <summary>
    /// ServiceFactory is used to create an instance of the WCF service. Only one static method exists here that create an instance of 
    /// ServicesClient and sends it back to the caller.
    /// </summary>
    internal class ServiceFactory
    {
        static internal NetStsAdmService.CommandExecuterClient GetService(string ServiceURL, NetworkCredential Credential)
        {
            BasicHttpBinding binding = new BasicHttpBinding();
            
            binding.MaxReceivedMessageSize = 50000000;
            // Redefine the limitation so that large files can be sent over
            XmlDictionaryReaderQuotas xmlDictionaryReaderQuotas = new XmlDictionaryReaderQuotas();
            xmlDictionaryReaderQuotas.MaxArrayLength = 50000000;
            xmlDictionaryReaderQuotas.MaxStringContentLength = 8192 * 8192;
            binding.ReaderQuotas = xmlDictionaryReaderQuotas;

            binding.SendTimeout = TimeSpan.FromMinutes(360);

            binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;

            Uri url = new Uri(ServiceURL);

            if (!url.OriginalString.EndsWith(Constants.WEBSERVICE_SFX))
                url = new Uri(url, Constants.WEBSERVICE_SFX);

            EndpointAddress serviceEndPoint = new EndpointAddress(url);
            NetStsAdmService.CommandExecuterClient sc = new NetStsAdmService.CommandExecuterClient(binding, serviceEndPoint);

            if (Credential != null)
                sc.ClientCredentials.Windows.ClientCredential = Credential;

            return sc;
        } 
    }
}